from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from random import randint as r
import pygame
from datetime import date
import os

pygame.mixer.init()
pygame.init()

root = Tk()
root.title("Сбеги из пещеры по инструкий своего друга")
root.geometry("1240x880+300+75")
root.resizable(False, False)

path_to_game = os.path.dirname(__file__)

stage = "menu_logo"
stage_other = "menu"
id_level = "none"

logospeedy = -0.1
logospeedx = -0.1
logoy = 50
logox = 240

logo = Image.open(path_to_game + "\\images\\logo.png")
logop = ImageTk.PhotoImage(logo)
labellogo = Label(root, image=logop)
labellogo.place(x=logox, y=logoy)

back = Image.open(path_to_game + "\\images\\back.png")
backp = ImageTk.PhotoImage(back)
help = Image.open(path_to_game + "\\images\\help.png")
helpp = ImageTk.PhotoImage(help)
helpbutton = Button(root, image=helpp, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("menu_help"))
helpbutton.place(x=1120, y=780)

switch_mode_button = Image.open(path_to_game + "\\images\\switch_mode_button.png")

width, height = switch_mode_button.size

switch_mode_button_sprite_parts = []
for y in range(0, height, 200):
    for x in range(0, width, 200):
        box = (x, y, min(x + 200, width), min(y + 200, height))
        sprite = switch_mode_button.crop(box)
        switch_mode_button_sprite_parts.append(sprite)
switch_mode_button_images = [ImageTk.PhotoImage(sp) for sp in switch_mode_button_sprite_parts]

labelswitch_mode_button = ttk.Label(root)
labelswitch_mode_button.grid(row=0, column=0)

help_switch_button_p1 = Button(root, image=switch_mode_button_images[0], borderwidth=0, highlightthickness=0, command=lambda: switch_mode(1))
help_switch_button_p2 = Button(root, image=switch_mode_button_images[1], borderwidth=0, highlightthickness=0, command=lambda: switch_mode(2))

help_switch_button = Image.open(path_to_game + "\\images\\help_switch_button.png")

width, height = help_switch_button.size

help_switch_button_sprite_parts = []
for y in range(0, height, 100):
    for x in range(0, width, 100):
        box = (x, y, min(x + 100, width), min(y + 100, height))
        sprite = help_switch_button.crop(box)
        help_switch_button_sprite_parts.append(sprite)
help_switch_button_images = [ImageTk.PhotoImage(sp) for sp in help_switch_button_sprite_parts]

labelhelp_switch_button = ttk.Label(root)
labelhelp_switch_button.grid(row=0, column=0)

help_switch_button_info = Button(root, image=help_switch_button_images[1], borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("menu_help"))
help_switch_button_info1 = Button(root, image=help_switch_button_images[0], borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("menu_help_switch"))

start = Image.open(path_to_game + "\\images\\start.png")
startp = ImageTk.PhotoImage(start)

playbutton = Button(root, image=startp, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("menu_level_select"))
playbutton.place(x=450, y=600)

back_select = Image.open(path_to_game + "\\images\\back_select.png")
back_selectp = ImageTk.PhotoImage(back_select)
back_selectbutton = Button(root, image=back_selectp, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("menu_logo"))
back_selectbutton.place(x=450, y=600)

level1 = Image.open(path_to_game + "\\images\\1 level.png")
level1p = ImageTk.PhotoImage(level1)
level1_button = Button(root, image=level1p, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_level(1))
level1_button.place(x=450, y=250)

level2 = Image.open(path_to_game + "\\images\\2 level.png")
level2p = ImageTk.PhotoImage(level2)
level2_button = Button(root, image=level2p, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_level(2))
level2_button.place(x=50, y=450)

level3 = Image.open(path_to_game + "\\images\\3 level.png")
level3p = ImageTk.PhotoImage(level3)
level3_button = Button(root, image=level3p, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_level(3))
level3_button.place(x=750, y=450)

info_level = Image.open(path_to_game + "\\images\\info level 1.png")
info_levelp = ImageTk.PhotoImage(info_level)
labelinfo_level = Label(root, image=info_levelp)

next_level_win = Image.open(path_to_game + "\\images\\next_level_win.png")
next_level_winp = ImageTk.PhotoImage(next_level_win)
next_level_winbutton = Button(root, image=next_level_winp, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("menu_logo"))
next_level_winbutton.place(x=450, y=600)
next_level_winbuttony = 0

game_over = Image.open(path_to_game + "\\images\\game_over.png")
game_overp = ImageTk.PhotoImage(game_over)
labelgame_over = Label(root, image=game_overp, background="#ca8600")
game_overy = 0
game_overspeedy = 0
game_overlowspeedy = 0

record_level1_P1 = "0:00"
win_level_P1 = "Не пройдено"
record_level1_P2 = "0:00"
win_level_P2 = "Не пройдено"

text_menu1 = ttk.Label(root, text="Кабан", font=("Calibri", 30), foreground="#000000")
text_menu1.place(x=150, y=100)

text_menu2 = ttk.Label(root, text="Кабан", font=("Calibri", 30), foreground="#000000")
text_menu2.place(x=100, y=200)

text_menu3 = ttk.Label(root, text="Кабан", font=("Calibri", 30), foreground="#000000")
text_menu3.place(x=350, y=350)

help_switch_music = False

def helper_switch_stage(a):
    global stage
    stage = a
    menu_show_images()
    print("hi")
    if stage == "game_level_start" or stage_other == "game":
        gameplay()

def helper_switch_level(id):
    global id_level, stage
    id_level = id
    if id_level == 1:
        stage = "menu_level_info"
    menu_show_images()

player_mode = 2

def switch_mode(a):
    global player_mode
    player_mode = a
    print(player_mode)

    
pygame.mixer.music.load(path_to_game + "\\music\\menu.mp3")
pygame.mixer.music.play(loops=-1)


def menu_animations():
    global logoy, logox, logospeedy, logospeedx, next_level_winbuttony, game_overy, game_overspeedy, game_overlowspeedy
    root.after(1, menu_animations)
    if stage == "menu_logo":
        logoy += logospeedy
        logox -= logospeedx

        labellogo.place(x=logox, y=logoy)

        if logoy < 0:
            logospeedy = 0.1
        elif logoy > 150:
            logospeedy = -0.1
        elif logox < 50:
            logospeedx = -0.1
        elif logox > 400:
            logospeedx = 0.1

    elif stage == "menu_help":
        logox -= logospeedx
        labellogo.place(x=logox, y=logoy)
        
        if logox < 50:
            logospeedx = -0.2
        elif logox > 400:
            logospeedx = 0.2
    elif stage == "menu_level_lose":
        if game_overlowspeedy < 3:
            game_overspeedy += 0.0075
            game_overy += game_overspeedy
        if next_level_winbuttony > 700:
            next_level_winbuttony -= 0.25
        if game_overy > 200:
            game_overspeedy = -3 + game_overlowspeedy
            game_overlowspeedy += 0.5
        next_level_winbutton.place(x=400, y=next_level_winbuttony)
        labelgame_over.place(x=225, y=game_overy)

def menu_show_images():
    global stage, logospeedx, logospeedy, logox, logoy, help_switch_music, next_level_winbuttony, game_overlowspeedy, game_overy, game_overspeedy
    text_menu1.place_forget()
    text_menu2.place_forget()
    text_menu3.place_forget()
    back_selectbutton.place_forget()
    level1_button.place_forget()
    level2_button.place_forget()
    level3_button.place_forget()
    playbutton.place_forget()
    helpbutton.place_forget()
    labellogo.place_forget()
    labelinfo_level.place_forget()
    lookbutton_lever.place_forget()
    lookbutton_fire.place_forget()
    lookbutton_water_machine.place_forget()
    help_switch_button_p1.place_forget()
    help_switch_button_p2.place_forget()
    help_switch_button_info.place_forget()
    help_switch_button_info1.place_forget()
    next_level_winbutton.place_forget()
    labelgame_over.place_forget()

    if stage == "menu_logo":
        logospeedy = -0.1
        logospeedx = -0.1
        logoy = 50
        logox = 240

        helpbutton.config(image=helpp, command=lambda: helper_switch_stage("menu_help"))
        helpbutton.place(x=1120, y=780)

        playbutton.config(command=lambda: helper_switch_stage("menu_level_select"))
        playbutton.place(x=450, y=600)

        labellogo.place(x=logox, y=logoy)

        labelbackground_level.place_forget()

        root.configure(bg='SystemButtonFace')

        if help_switch_music == True:
            pygame.mixer.music.load(path_to_game + "\\music\\menu.mp3")
            pygame.mixer.music.play(loops=-1)
            help_switch_music = False

    elif stage == "menu_help":
        logospeedy = -0.2
        logospeedx = -0.2
        logoy = 425
        logox = 240

        text_menu1.config(text="Играть в эту игру надо вдвоем!", font=("Calibri", 50), foreground="#FF0000", background="")
        text_menu1.place(x=150, y=100)

        text_menu2.config(text="Вы застряли в пещере! Но у вашего друга есть инструкция по побегу\nтолько сможет ли он вам все обьяснить...\nВам запрещено смотреть в инструкцию, а вашему другу на ваш экран", font=("Calibri", 25), background="")
        text_menu2.place(x=100, y=200)

        text_menu3.config(text="Игра сделана Ерином Денисом", font=("Calibri", 30), foreground="#0011FF", background="")
        text_menu3.place(x=350, y=350)

        playbutton.place_forget()

        helpbutton.config(image=backp, command=lambda: helper_switch_stage("menu_logo"))
        helpbutton.place(x=1120, y=780)

        help_switch_button_info1.place(x=1095, y=300)
    elif stage == "menu_help_switch":
        logospeedy = -0.2
        logospeedx = -0.2
        logoy = 425
        logox = 240

        text_menu1.config(text=' Ну или если хотите играть один\nнажмите кнопку с надписью "P1"', font=("Calibri", 45), foreground="#970000", background="")
        text_menu1.place(x=200, y=100)

        text_menu2.config(text=' Чтобы вернуть все как было\nнажмите кнопку с надписью "P2"', font=("Calibri", 45), foreground="#0300AA", background="")
        text_menu2.place(x=200, y=400)

        help_switch_button_info.place(x=50, y=300)

        help_switch_button_p1.place(x=350, y=600)
        help_switch_button_p2.place(x=750, y=600)
        
    elif stage == "menu_level_select":
        text_menu1.config(text="Выберите уровень", background="", font=("Calibri", 100), foreground="#000000")
        text_menu1.place(x=100, y=0)

        back_selectbutton.place(x=450, y=700)
        back_selectbutton.config(command=lambda: helper_switch_stage("menu_logo"))

        level1_button.place(x=450, y=250)
        level2_button.place(x=50, y=450)
        level3_button.place(x=750, y=450)
        if id_level == 2 or id_level == 3:
            text_menu2.config(text="Можно выбрать только первую пещеру!", font=("Calibri", 35), foreground="#FF0000")
            text_menu2.place(x=225, y=175)
    elif stage == "menu_level_info":
        labelinfo_level.place(x=0,y=0)

        text_menu1.config(text="Обучающая пещера!", font=("Calibri", 42), background="#dbdbdb", foreground="#000000")
        text_menu1.place(x=700, y=50)

        text_menu2.config(text="Время: 5 минут\nОшибок: 3\nЗадач: 3", font=("Calibri", 50), background="#dbdbdb", foreground="#000000")
        text_menu2.place(x=700, y=225)
        
        text_menu3.place(x=75, y=550)

        back_selectbutton.config(command=lambda: helper_switch_stage("menu_level_select"))
        back_selectbutton.place(x=790, y=700)
        back_selectbutton.lift() 

        playbutton.config(command=lambda: helper_switch_stage("game_level_start"))
        playbutton.place(x=790, y=505)
        playbutton.lift() 
        if player_mode == 1:
            text_menu3.config(text="Статус: " + win_level_P1 + "\n\nРекорд по времени: " + record_level1_P1, font=("Calibri", 50), background="#dbdbdb", foreground="#000000")
        elif player_mode == 2:
            text_menu3.config(text="Статус: " + win_level_P2 + "\n\nРекорд по времени: " + record_level1_P2, font=("Calibri", 50), background="#dbdbdb", foreground="#000000")
    elif stage == "menu_level_win":
        text_menu1.config(text="Обучающая пещера", font=("Calibri", 42), background='#ca8600', foreground="#FF7300")
        text_menu1.place(x=380, y=50)

        text_menu2.config(text="Поздравляю! Вы победили!", font=("Calibri", 50), background='#ca8600', foreground="#966100")
        text_menu2.place(x=200, y=250)

        text_menu3.place(x=150, y=450)

        next_level_winbutton.place(x=400, y=700)
        labelbackground_level.place_forget()

        pygame.mixer.music.load(path_to_game + "\\music\\win_level.mp3")
        pygame.mixer.music.play(loops=1)
        help_switch_music = True
        if player_mode == 1:
            text_menu3.config(text="Оставалось времени: " + record_level1_P1, font=("Calibri", 60), background='#ca8600', foreground="#966100")
            P1_cave_number1.place_forget()
            P1_cave_number2.place_forget()
            P1_cave_number3.place_forget()
            P1_cave_number4.place_forget()
            P1_cave_images1.place_forget()
            P1_cave_images2.place_forget()
            P1_cave_images3.place_forget()
            P1_cave_fire.place_forget()
        elif player_mode == 2:
            text_menu3.config(text="Оставалось времени: " + record_level1_P2, font=("Calibri", 60), background='#ca8600', foreground="#966100")
    elif stage == "menu_level_lose":

        next_level_winbutton.place(x=400, y=700)
        labelbackground_level.place_forget()

        pygame.mixer.music.load(path_to_game + "\\music\\game_over.mp3")
        pygame.mixer.music.play(loops=1)
        help_switch_music = True    

        next_level_winbuttony = 1500
        game_overlowspeedy = 0
        game_overy = -700
        game_overspeedy = 0

loading_time = 0
loading_current_frame = 0
loading_music_id = 0
loading_text_id = 0
current_date = date.today()
formatted_date = current_date.strftime("%d")

loading = Image.open(path_to_game + "\\images\\loading.png")

width, height = loading.size
loading_sprite_parts = []
for y in range(0, height, 300):
    for x in range(0, width, 300):
        box = (x, y, x + 300, y + 300)
        sprite = loading.crop(box)
        loading_sprite_parts.append(sprite)
loading_images = [ImageTk.PhotoImage(sp) for sp in loading_sprite_parts]

loading_animation_label = ttk.Label(root)
loading_animation_label.grid(row=0, column=0)

loadingBar = ttk.Progressbar(orient="horizontal", length=1000, value=0)
loadingBar.place()
loadingBar.place_configure

lattice = Image.open(path_to_game + "\\images\\lattice.png")

width, height = lattice.size

lattice_sprite_parts = []
for y in range(0, height, 400):
    for x in range(0, width, 500):
        box = (x, y, min(x + 500, width), min(y + 400, height))
        sprite = lattice.crop(box)
        lattice_sprite_parts.append(sprite)
lattice_images = [ImageTk.PhotoImage(sp) for sp in lattice_sprite_parts]

labellattice = ttk.Label(root, background='#ca8600')
labellattice.grid(row=0, column=0)


lever = Image.open(path_to_game + "\\images\\lever.png")

width, height = lever.size

lever_sprite_parts = []
for y in range(0, height, 186):
    for x in range(0, width, 186):
        box = (x, y, min(x + 186, width), min(y + 186, height))
        sprite = lever.crop(box)
        lever_sprite_parts.append(sprite)
lever_images = [ImageTk.PhotoImage(sp) for sp in lever_sprite_parts]

labellever = ttk.Label(root, background='#ca8600')
labellever.grid(row=0, column=0)

water_machine = Image.open(path_to_game + "\\images\\water_machine.png")

width, height = water_machine.size

water_machine_sprite_parts = []
for y in range(0, height, 300):
    for x in range(0, width, 300):
        box = (x, y, min(x + 300, width), min(y + 300, height))
        sprite = water_machine.crop(box)
        water_machine_sprite_parts.append(sprite)
water_machine_images = [ImageTk.PhotoImage(sp) for sp in water_machine_sprite_parts]

labelwater_machine = ttk.Label(root, background='#ca8600')
labelwater_machine.grid(row=0, column=0)

background_level = Image.open(path_to_game + "\\images\\background.png")
background_levelp = ImageTk.PhotoImage(background_level)
labelbackground_level = Label(root, image=background_levelp)

look = Image.open(path_to_game + "\\images\\look.png")
lookp = ImageTk.PhotoImage(look)
back_level = Image.open(path_to_game + "\\images\\back_level.png")
back_level = back_level.resize((150, 150))
back_levelp = ImageTk.PhotoImage(back_level)
lookbutton_lever = Button(root, image=lookp, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("game_lever_around"))
lookbutton_fire = Button(root, image=lookp, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("game_fire_around"))
lookbutton_water_machine = Button(root, image=lookp, borderwidth=0, highlightthickness=0, command=lambda: helper_switch_stage("game_water_machine_around"))

lever_around = Image.open(path_to_game + "\\images\\lever_around.png")

width, height = lever_around.size

lever_around_sprite_parts = []
for y in range(0, height, 450):
    for x in range(0, width, 450):
        box = (x, y, min(x + 450, width), min(y + 450, height))
        sprite = lever_around.crop(box)
        lever_around_sprite_parts.append(sprite)
lever_around_images = [ImageTk.PhotoImage(sp) for sp in lever_around_sprite_parts]

labellever_around = ttk.Label(root, background='#ca8600')
labellever_around.grid(row=0, column=0)

fire = Image.open(path_to_game + "\\images\\fire.png")

width, height = fire.size

fire_sprite_parts = []
for y in range(0, height, 250):
    for x in range(0, width, 250):
        box = (x, y, min(x + 250, width), min(y + 250, height))
        sprite = fire.crop(box)
        fire_sprite_parts.append(sprite)
fire_images = [ImageTk.PhotoImage(sp) for sp in fire_sprite_parts]

labelfire = ttk.Label(root, background='#ca8600')
labelfire.grid(row=0, column=0)

fire_around = Image.open(path_to_game + "\\images\\fire_around.png")

width, height = fire_around.size

fire_around_sprite_parts = []
for y in range(0, height, 450):
    for x in range(0, width, 450):
        box = (x, y, min(x + 450, width), min(y + 450, height))
        sprite = fire_around.crop(box)
        fire_around_sprite_parts.append(sprite)
fire_around_images = [ImageTk.PhotoImage(sp) for sp in fire_around_sprite_parts]

labelfire_around = ttk.Label(root, background='#ca8600')
labelfire_around.grid(row=0, column=0)

fire_button = Image.open(path_to_game + "\\images\\fire_button.png")

width, height = fire_button.size

fire_button_sprite_parts = []
for y in range(0, height, 75):
    for x in range(0, width, 75):
        box = (x, y, min(x + 75, width), min(y + 75, height))
        sprite = fire_button.crop(box)
        fire_button_sprite_parts.append(sprite)
fire_button_images = [ImageTk.PhotoImage(sp) for sp in fire_button_sprite_parts]

labelfire_button = ttk.Label(root, background='#ca8600')
labelfire_button.grid(row=0, column=0)


fire_button_up = Button(root, image=fire_button_images[0], borderwidth=0, highlightthickness=0, command=lambda: logic_fire("up"))
fire_button_down = Button(root, image=fire_button_images[2], borderwidth=0, highlightthickness=0, command=lambda: logic_fire("down"))
fire_button_yes = Button(root, image=fire_button_images[1], borderwidth=0, highlightthickness=0, command=lambda: logic_fire("yes"))

water_machine_around = Image.open(path_to_game + "\\images\\water_machine_around.png")

width, height = water_machine_around.size

water_machine_around_sprite_parts = []
for y in range(0, height, 450):
    for x in range(0, width, 450):
        box = (x, y, min(x + 450, width), min(y + 450, height))
        sprite = water_machine_around.crop(box)
        water_machine_around_sprite_parts.append(sprite)
water_machine_around_images = [ImageTk.PhotoImage(sp) for sp in water_machine_around_sprite_parts]

labelwater_machine_around = ttk.Label(root, background='#ca8600')
labelwater_machine_around.grid(row=0, column=0)

water_machine_button = Image.open(path_to_game + "\\images\\water_machine_button.png")

width, height = water_machine_button.size

water_machine_button_sprite_parts = []
for y in range(0, height, 75):
    for x in range(0, width, 75):
        box = (x, y, min(x + 75, width), min(y + 75, height))
        sprite = water_machine_button.crop(box)
        water_machine_button_sprite_parts.append(sprite)
water_machine_button_images = [ImageTk.PhotoImage(sp) for sp in water_machine_button_sprite_parts]

labelwater_machine_button = ttk.Label(root, background='#ca8600')
labelwater_machine_button.grid(row=0, column=0)

water_machine_button_strong = Button(root, image=water_machine_button_images[0], borderwidth=0, highlightthickness=0, command=lambda: logic_water_machine("strong"))
water_machine_button_normal = Button(root, image=water_machine_button_images[1], borderwidth=0, highlightthickness=0, command=lambda: logic_water_machine("normal"))
water_machine_button_weak = Button(root, image=water_machine_button_images[2], borderwidth=0, highlightthickness=0, command=lambda: logic_water_machine("weak"))
water_machine_button_up = Button(root, image=water_machine_button_images[3], borderwidth=0, highlightthickness=0, command=lambda: logic_water_machine("up"))
water_machine_button_down = Button(root, image=water_machine_button_images[4], borderwidth=0, highlightthickness=0, command=lambda: logic_water_machine("down"))

water_machine_indicator = Image.open(path_to_game + "\\images\\water_machine_indicator.png")

width, height = water_machine_indicator.size

water_machine_indicator_sprite_parts = []
for y in range(0, height, 300):
    for x in range(0, width, 30):
        box = (x, y, min(x + 30, width), min(y + 300, height))
        sprite = water_machine_indicator.crop(box)
        water_machine_indicator_sprite_parts.append(sprite)
water_machine_indicator_images = [ImageTk.PhotoImage(sp) for sp in water_machine_indicator_sprite_parts]

labelwater_machine_indicator = ttk.Label(root)
labelwater_machine_indicator.grid(row=0, column=0)

P1_cave_number = Image.open(path_to_game + "\\images\\P1_cave_numbers.png")

width, height = P1_cave_number.size

P1_cave_number_sprite_parts = []
for y in range(0, height, 50):
    for x in range(0, width, 50):
        box = (x, y, min(x + 50, width), min(y + 50, height))
        sprite = P1_cave_number.crop(box)
        P1_cave_number_sprite_parts.append(sprite)
P1_cave_number_images = [ImageTk.PhotoImage(sp) for sp in P1_cave_number_sprite_parts]

P1_cave_number = ttk.Label(root, background='#ca8600')
P1_cave_number.grid(row=0, column=0)
P1_cave_number1 = Label(root, image=P1_cave_number_images[0])
P1_cave_number2 = Label(root, image=P1_cave_number_images[0])
P1_cave_number3 = Label(root, image=P1_cave_number_images[0])
P1_cave_number4 = Label(root, image=P1_cave_number_images[0])

P1_cave_images = Image.open(path_to_game + "\\images\\P1_cave_images.png")

width, height = P1_cave_images.size

P1_cave_images_sprite_parts = []
for y in range(0, height, 50):
    for x in range(0, width, 50):
        box = (x, y, min(x + 50, width), min(y + 50, height))
        sprite = P1_cave_images.crop(box)
        P1_cave_images_sprite_parts.append(sprite)
P1_cave_images_images = [ImageTk.PhotoImage(sp) for sp in P1_cave_images_sprite_parts]

P1_cave_images = ttk.Label(root, background='#ca8600')
P1_cave_images.grid(row=0, column=0)
P1_cave_images1 = Label(root, image=P1_cave_images_images[0])
P1_cave_images2 = Label(root, image=P1_cave_images_images[0])
P1_cave_images3 = Label(root, image=P1_cave_images_images[0])

P1_cave_fire = Image.open(path_to_game + "\\images\\P1_cave_fire.png")

width, height = P1_cave_fire.size

P1_cave_fire_sprite_parts = []
for y in range(0, height, 100):
    for x in range(0, width, 100):
        box = (x, y, min(x + 100, width), min(y + 100, height))
        sprite = P1_cave_fire.crop(box)
        P1_cave_fire_sprite_parts.append(sprite)
P1_cave_fire_images = [ImageTk.PhotoImage(sp) for sp in P1_cave_fire_sprite_parts]

P1_cave_fire = ttk.Label(root, background='#ca8600')
P1_cave_fire.grid(row=0, column=0)
P1_cave_fire = Label(root, image=P1_cave_fire_images[0])

lever_id = 0
fire_id = 0
lattice_id = 0
room_id = 0
water_machine_water_col = 0
time_minutes_level = 4
time_seconds_level = 60
lever_clear = False
fire_clear = False
water_machine_clear = False
fire_size_for_win_P1 = 0
lever_action_id_for_win_P1 = 0
true_image_number_P1 = 0
P1cn1 = 0
P1cn2 = 0
P1cn3 = 0
P1cn4 = 0
col_error = 0

def gameplay():
    global loading_text_id, loading_music_id, lever_id, fire_id, lattice_id, room_id, water_machine_water_col, time_minutes_level, time_seconds_level, stage_other, col_error, lever_clear, fire_clear, water_machine_clear, win_col_quest, fire_size_for_win_P1, lever_action_id_for_win_P1, true_image_number_P1, P1cn1, P1cn2, P1cn3, P1cn4
    if stage == "game_level_start":
        loadingBar.place(x=125,y=700)
        loadingBar.start(150)
        root.after(15000, loading_end)

        stage_other = "game"
        loading_music_id = r(1, 4)
        loading_text_id = r(1, 5)
        lever_id = r(1, 4)
        fire_id = r(1, 3)
        lattice_id = r(0, 1)
        room_id = r(1, 9)
        water_machine_water_col = r(0, 10)
        win_col_quest = 3
        time_minutes_level = 4
        time_seconds_level = 60
        col_error = 0
        lever_clear = False
        fire_clear = False
        water_machine_clear = False
        function_win_level()

        text_menu1.config(text="Загрузка...", font=("Calibri", 75), background="", foreground="#000000")
        text_menu1.place(x=375, y=100)

        loading_animation()

        pygame.mixer.music.stop()
        pygame.mixer.music.load(path_to_game + "\\music\\random_music_loading\\" + str(loading_music_id) + ".mp3")
        pygame.mixer.music.play(loops=1)

        loading_animation_label.place(x=460, y=300)
        if player_mode == 1:
            fire_size_for_win_P1 = r(1, 3)
            lever_action_id_for_win_P1 = r(1, 3)
            true_image_number_P1 = r(1, 4)
            lever_id = 5
            lattice_id = 0
            room_id = r(0, 10)
            P1cn1 = r(1, 3)
            P1cn2 = r(1, 3)
            P1cn3 = r(1, 3)
            P1cn4 = r(1, 3)
            P1_cave_images1.config(image=P1_cave_images_images[r(0, 4)], borderwidth=0, highlightthickness=0, background='#ca8600')
            P1_cave_images2.config(image=P1_cave_images_images[r(0, 4)], borderwidth=0, highlightthickness=0, background='#ca8600')
            P1_cave_images3.config(image=P1_cave_images_images[r(0, 4)], borderwidth=0, highlightthickness=0, background='#ca8600')
        if loading_text_id == 1:
            text_menu2.config(text="Учителя, вообще-то можно было ходить по земле!", font=("Calibri", 37), background="", foreground="#000000")
            text_menu2.place(x=100, y=600)
        elif loading_text_id == 2:
            text_menu2.config(text="Сегодня " + str(formatted_date) + " число", font=("Calibri", 65), background="", foreground="#000000")
            text_menu2.place(x=275, y=600)
        elif loading_text_id == 3:
            text_menu2.config(text="С наступающим новым годом!", font=("Calibri", 55), background="", foreground="#000000")
            text_menu2.place(x=150, y=600)
        elif loading_text_id == 4:
            text_menu2.config(text="Приготовьтесь сбегать из пещеры...", font=("Calibri", 50), background="", foreground="#000000")
            text_menu2.place(x=125, y=600)
        elif loading_text_id == 5:
            text_menu2.config(text="На самом деле это не настоящая загрузка ;)", font=("Calibri", 45), background="", foreground="#000000")
            text_menu2.place(x=75, y=600)
    elif stage == "game_level":
        loading_animation_label.place_forget()
        labellever_around.place_forget()
        labelfire_around.place_forget()
        labelwater_machine_around.place_forget()
        fire_button_up.place_forget()
        fire_button_down.place_forget()
        fire_button_yes.place_forget()
        water_machine_button_strong.place_forget()
        water_machine_button_normal.place_forget()
        water_machine_button_weak.place_forget()
        water_machine_button_up.place_forget()
        water_machine_button_down.place_forget()
        labelwater_machine_indicator.place_forget()

        labelbackground_level.place(x=0, y=0)
        labelbackground_level.lower()

        text_menu1.place(x=525, y=25)
        text_menu2.config(text="0" + str(id_level) + str(room_id), font=("Calibri", 50), background='#ca8600', foreground="#b47500")
        text_menu2.place(x=975, y=75)

        lattice_frame_id = (int(lattice_id) - 1) % len(lattice_images)
        labellattice.config(image=lattice_images[lattice_frame_id])
        labellattice.lift()
        labellattice.place(x=370, y=225)
        root.configure(bg="#ca8600")

        lever_frame_id = (int(lever_id) - 1) % len(lever_images)
        labellever.config(image=lever_images[lever_frame_id])
        labellever.place(x=150, y=450)

        fire_frame_id = (int(fire_id) - 1) % len(lever_images)
        labelfire.config(image=fire_images[fire_frame_id])
        labelfire.place(x=900, y=375)

        labelwater_machine.config(image=water_machine_images[1])
        labelwater_machine.place(x=75, y=125)
        lookbutton_lever.config(image=lookp, command=lambda: helper_switch_stage("game_lever_around"))
        lookbutton_lever.place(x=200, y=650)
        lookbutton_fire.config(image=lookp, command=lambda: helper_switch_stage("game_fire_around"))
        lookbutton_fire.place(x=1000, y=650)
        lookbutton_water_machine.config(image=lookp, command=lambda: helper_switch_stage("game_water_machine_around"))
        lookbutton_water_machine.place(x=205, y=390)
        #labelbackground_level.lower()
        #labelbackground_level.place(x=0,y=0)
        if lever_clear == True and player_mode == 2:
            labellever.config(image=lever_images[lever_frame_id + 4])
            labellever.place(x=100, y=400)
        if lever_clear == False and player_mode == 1:
            labellever.config(image=lever_images[0])
        if lever_clear == True and player_mode == 1:
            labellever.config(image=lever_images[4])
        if water_machine_clear == False and player_mode == 2:
            labelwater_machine.config(image=water_machine_images[0])
            labelwater_machine.place(x=75, y=125)
        if water_machine_clear == False and player_mode == 1:
            labelwater_machine.config(image=water_machine_images[2])
            labelwater_machine.place(x=75, y=125)
        if water_machine_clear == True and player_mode == 1:
            labelwater_machine.config(image=water_machine_images[3])
            labelwater_machine.place(x=75, y=125)
        if player_mode == 1:
            text_menu2.config(text=str(room_id), font=("Calibri", 50), background='#ca8600', foreground="#b47500")
            P1_cave_number1.config(image=P1_cave_number_images[P1cn1 - 1], borderwidth=0, highlightthickness=0, background='#ca8600')
            P1_cave_number1.place(x=75,y=200)
            P1_cave_number1.lift()
            P1_cave_number2.config(image=P1_cave_number_images[P1cn2 - 1], borderwidth=0, highlightthickness=0, background='#ca8600')
            P1_cave_number2.place(x=300,y=500)
            P1_cave_number2.lift()
            P1_cave_number3.config(image=P1_cave_number_images[P1cn3 - 1], borderwidth=0, highlightthickness=0, background='#ca8600')
            P1_cave_number3.place(x=1100,y=450)
            P1_cave_number3.lift()
            P1_cave_number4.config(image=P1_cave_number_images[P1cn4 - 1], borderwidth=0, highlightthickness=0, background='#ca8600')
            P1_cave_number4.place(x=800,y=150)
            P1_cave_number4.lift()
            P1_cave_images1.place(x=250, y=100)
            P1_cave_images1.lift()
            P1_cave_images2.place(x=900, y=350)
            P1_cave_images2.lift()
            P1_cave_images3.place(x=100, y=750)
            P1_cave_images3.lift()
            P1_cave_fire.config(image=P1_cave_fire_images[fire_size_for_win_P1 - 1], borderwidth=0, highlightthickness=0, background='#ca8600')
            P1_cave_fire.place(x=1025,y=300)
            P1_cave_fire.lift()
            if true_image_number_P1 == 1:
                P1_cave_number1.config(image=P1_cave_number_images[lever_action_id_for_win_P1 + 2])
            elif true_image_number_P1 == 2:
                P1_cave_number2.config(image=P1_cave_number_images[lever_action_id_for_win_P1 + 2])
            elif true_image_number_P1 == 3:
                P1_cave_number3.config(image=P1_cave_number_images[lever_action_id_for_win_P1 + 2])
            elif true_image_number_P1 == 4:
                P1_cave_number4.config(image=P1_cave_number_images[lever_action_id_for_win_P1 + 2])
    elif stage == "game_lever_around":
        text_menu1.place(x=525, y=25)
        text_menu2.config(text="SPACE-Опустить рычаг",  font=("Calibri", 39), foreground="#FF0000")
        text_menu2.place(x=25,y=100)

        lever_frame_id = (int(lever_id) - 1) % len(lever_around_images)
        if lever_clear == True and player_mode == 2:
            labellever_around.config(image=lever_around_images[lever_frame_id + 4])
        elif lever_clear == False and player_mode == 2:
            labellever_around.config(image=lever_around_images[lever_frame_id])
        if lever_clear == False and player_mode == 1:
            labellever_around.config(image=lever_around_images[0])
        elif lever_clear == True and player_mode == 1:
            labellever_around.config(image=lever_around_images[4])
        labellever_around.place(x=420, y=225)

        labelwater_machine.place_forget()
        labellever.place_forget()
        labellattice.place_forget()
        labelfire.place_forget()
        labelbackground_level.place_forget()

        if player_mode == 1:
            P1_cave_number1.place_forget()
            P1_cave_number2.place_forget()
            P1_cave_number3.place_forget()
            P1_cave_number4.place_forget()
            P1_cave_images1.place_forget()
            P1_cave_images2.place_forget()
            P1_cave_images3.place_forget()
            P1_cave_fire.place_forget()
        
        lookbutton_lever.config(image=back_levelp, command=lambda: helper_switch_stage("game_level"))
        lookbutton_lever.place(x=580,y=700)
        logic_lever(event)
    elif stage == "game_fire_around":
        text_menu1.place(x=525, y=25)

        fire_frame_id = (int(fire_id) - 1) % len(fire_around_images)
        labelfire_around.config(image=fire_around_images[fire_frame_id])
        labelfire_around.place(x=420, y=225)

        labelwater_machine.place_forget()
        labellever.place_forget()
        labellattice.place_forget()
        labelfire.place_forget()
        labelbackground_level.place_forget()

        lookbutton_lever.config(image=back_levelp, command=lambda: helper_switch_stage("game_level"))
        lookbutton_lever.place(x=580,y=700)

        fire_button_up.place(x=250,y=500)
        fire_button_down.place(x=250,y=700)
        fire_button_yes.place(x=250,y=600)
        if player_mode == 1:
            P1_cave_number1.place_forget()
            P1_cave_number2.place_forget()
            P1_cave_number3.place_forget()
            P1_cave_number4.place_forget()
            P1_cave_images1.place_forget()
            P1_cave_images2.place_forget()
            P1_cave_images3.place_forget()
            P1_cave_fire.place_forget()
    elif stage == "game_water_machine_around":
        text_menu2.place_forget()

        if water_machine_clear == True:
            labelwater_machine_around.config(image=water_machine_around_images[1])
        elif water_machine_clear == False:
            labelwater_machine_around.config(image=water_machine_around_images[0])
            
        labelwater_machine_around.place(x=420, y=225)

        labelwater_machine.place_forget()
        labellever.place_forget()
        labellattice.place_forget()
        labelfire.place_forget()
        labelbackground_level.place_forget()

        water_machine_button_strong.place(x=500,y=300)
        water_machine_button_normal.place(x=500,y=400)
        water_machine_button_weak.place(x=500,y=500)
        water_machine_button_up.place(x=600,y=300)
        water_machine_button_down.place(x=600,y=500)
        labelwater_machine_indicator.config(image=water_machine_indicator_images[water_machine_water_col])
        labelwater_machine_indicator.place(x=750, y=300)
        lookbutton_lever.config(image=back_levelp, command=lambda: helper_switch_stage("game_level"))
        lookbutton_lever.place(x=580,y=700)
        if player_mode == 1:
            P1_cave_number1.place_forget()
            P1_cave_number2.place_forget()
            P1_cave_number3.place_forget()
            P1_cave_number4.place_forget()
            P1_cave_images1.place_forget()
            P1_cave_images2.place_forget()
            P1_cave_images3.place_forget()
            P1_cave_fire.place_forget()
            water_machine_button_strong.place(x=500,y=400)
            water_machine_button_normal.place_forget()
            water_machine_button_weak.place_forget()
            text_menu2.config(text="?",  font=("Calibri", 50), background="#767676", foreground="#0300C9")
            text_menu2.place(x=800,y=400)
            text_menu2.lift()

def loading_animation():
    global loading_current_frame
    loading_animation_label.config(image=loading_images[loading_current_frame])
    loading_current_frame = (loading_current_frame + 1) % len(loading_images)
    if stage == "game_level_start":
        root.after(150, loading_animation)

def loading_end():
    global stage
    stage = "game_level"
    pygame.mixer.music.load(path_to_game + "\\music\\level.mp3")
    pygame.mixer.music.play(loops=2)
    text_menu1.place_forget()
    text_menu2.place_forget()
    loadingBar.place_forget()
    loadingBar.stop()
    timer()
    gameplay()

def timer():
    global time_seconds_level, time_minutes_level, stage, stage_other
    text_menu1.config(text=str(time_minutes_level) + ":" + str(time_seconds_level), font=("Calibri", 100), background="#1A2036", foreground="#FF0000")
    text_menu1.place(x=525, y=25)
    timer_id = root.after(int(1000 / (1 + col_error)), timer)
    if time_seconds_level == 0:
        time_minutes_level -= 1
        time_seconds_level = 60
    elif time_minutes_level < 0:
        stage_other = "menu"
        func = lambda: helper_switch_stage("menu_level_lose")
        func()
        text_menu1.config(text="")
        labellever.place_forget()
        labellattice.place_forget()
        labellever_around.place_forget()
        labelfire.place_forget()
        labelfire_around.place_forget()
        fire_button_up.place_forget()
        fire_button_yes.place_forget()
        fire_button_down.place_forget()
        labelwater_machine.place_forget()
        labelwater_machine_around.place_forget()
        water_machine_button_strong.place_forget()
        water_machine_button_normal.place_forget()
        water_machine_button_weak.place_forget()
        water_machine_button_up.place_forget()
        water_machine_button_down.place_forget()
        labelwater_machine_indicator.place_forget()
        P1_cave_number1.place_forget()
        P1_cave_number2.place_forget()
        P1_cave_number3.place_forget()
        P1_cave_number4.place_forget()
        P1_cave_images1.place_forget()
        P1_cave_images2.place_forget()
        P1_cave_images3.place_forget()
        P1_cave_fire.place_forget()
        root.after_cancel(timer_id)
    elif win_col_quest == 0:
        root.after_cancel(timer_id)
    if win_col_quest > 0:
        time_seconds_level -= 1
    if col_error > 2:
        func = lambda: helper_switch_stage("menu_level_lose")
        func()        
        labellever.place_forget()
        labellattice.place_forget()
        labellever_around.place_forget()
        labelfire.place_forget()
        labelfire_around.place_forget()
        fire_button_up.place_forget()
        fire_button_yes.place_forget()
        fire_button_down.place_forget()
        labelwater_machine.place_forget()
        labelwater_machine_around.place_forget()
        water_machine_button_strong.place_forget()
        water_machine_button_normal.place_forget()
        water_machine_button_weak.place_forget()
        water_machine_button_up.place_forget()
        water_machine_button_down.place_forget()
        labelwater_machine_indicator.place_forget()
        P1_cave_number1.place_forget()
        P1_cave_number2.place_forget()
        P1_cave_number3.place_forget()
        P1_cave_number4.place_forget()
        P1_cave_images1.place_forget()
        P1_cave_images2.place_forget()
        P1_cave_images3.place_forget()
        P1_cave_fire.place_forget()
        root.after_cancel(timer_id)

time_lever_true = 0
ticks = 0
win_col_quest = 3

sound_yes = pygame.mixer.Sound(path_to_game + "\\sound\\yes.mp3")
sound_tick = pygame.mixer.Sound(path_to_game + "\\sound\\tick.mp3")
sound_WM_clear = pygame.mixer.Sound(path_to_game + "\\sound\\water_machine_clear.mp3")

def reset_timer_lever():
    global time_lever_true, col_error
    time_lever_true = 0
    print("Сброс счетчика:", time_lever_true)

def logic_lever(event):
    global time_lever_true, reset_timer_id, col_error, lever_clear, ticks, win_col_quest
    if stage == "game_lever_around":
        if lever_clear == False:
            if lever_id == 1:
                if event.type == '2': #Нажато
                    if event.keysym == 'space' and time_lever_true < 26:
                        time_lever_true += 1
                        root.after_cancel(reset_timer_id)
                        reset_timer_id = root.after(50, reset_timer_lever)
                    elif event.keysym == 'space' and time_lever_true > 25:
                        time_lever_true = 0
                        col_error += 1
                        reset_timer_id = root.after(50, reset_timer_lever)
                elif event.type == '3': #Отжато
                    if  event.keysym == 'space' and 0 < time_lever_true < 26:
                        print("it's good")
                        lever_clear = True
                        win_col_quest -= 1
            elif lever_id == 2:
                if lattice_id == 1:
                    d = str(time_seconds_level)
                    if event.type == '3': #Отжато
                        if event.keysym == 'space' and '5' in d:
                            print("it's good")
                            lever_clear = True
                            win_col_quest -= 1
                        else:
                            col_error += 1
                            print("bad")
                elif lattice_id == 0:
                    if event.type == '2' and event.keysym == 'space':
                        time_lever_true += 1
                        root.after_cancel(reset_timer_id)
                        reset_timer_id = root.after(50, reset_timer_lever)
                        if time_lever_true == 100:
                            sound_yes.play()
                    elif event.type == '3': #Отжато
                        if event.keysym == 'space':
                            if 100 < time_lever_true < 115:
                                print("it's good")
                                win_col_quest -= 1
                                lever_clear = True
                            elif time_lever_true < 100 or time_lever_true > 215:
                                time_lever_true = 0
                                col_error += 1
            elif lever_id == 3:
                if event.type == '2': #Нажато
                    if event.keysym == 'space' and time_lever_true < 27:
                        time_lever_true += 1
                        root.after_cancel(reset_timer_id)
                        reset_timer_id = root.after(50, reset_timer_lever)
                    elif event.keysym == 'space' and time_lever_true > 26:
                        ticks += 1
                        sound_tick.play()
                elif event.type == '3': #Отжато
                    if event.keysym == 'space' and ticks > 6 and ticks < 11:
                        print("it's good")
                        win_col_quest -= 1
                        lever_clear = True
                    elif event.keysym == 'space' and (ticks < 6 or ticks > 11):
                        time_lever_true = 0
                        ticks = 0
                        col_error += 1
                        reset_timer_id = root.after(50, reset_timer_lever)
                        print("bad")
            elif lever_id == 4:
                if col_error == 0:
                    if event.type == '3': #Отжато
                        if event.keysym == 'space':
                            print("it's good")
                            win_col_quest -= 1
                            lever_clear = True
                elif col_error > 0:
                    if event.type == '2' and fire_clear == True: #Нажато
                        if event.keysym == 'space' and time_lever_true < 6:
                            time_lever_true += 1
                            root.after_cancel(reset_timer_id)
                            reset_timer_id = root.after(50, reset_timer_lever)
                        elif event.keysym == 'space' and time_lever_true > 5:
                            time_lever_true = 0
                            col_error += 1
                            reset_timer_id = root.after(50, reset_timer_lever)
                    elif event.type == '3' and fire_clear == True: #Отжато
                        if  event.keysym == 'space' and 0 < time_lever_true < 6:
                            print("it's good")
                            win_col_quest -= 1
                            lever_clear = True
                    else:
                        col_error += 1
            if lever_id == 5:
                if event.type == '3': #Отжато
                    if event.keysym == 'space' and win_col_quest == lever_action_id_for_win_P1:
                        print("it's good")
                        lever_clear = True
                        win_col_quest -= 1
                    else:
                        col_error += 1

def logic_fire(active):
    global fire_id, fire_clear, col_error, win_col_quest
    print("active =", active)
    if active == "up" and fire_id < 3:
        fire_id += 1
    elif active == "down" and fire_id > 1:
        fire_id -= 1
    elif active == "yes" and fire_clear == False:
        if room_id % 2 != 0 and player_mode == 2:
            print("Bbbb")
            if lattice_id == 1:
                if room_id < 4 and fire_id == 1:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                elif room_id > 3 and room_id < 7 and fire_id == 2:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                elif room_id > 6 and fire_id == 3:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                else:
                    col_error += 1
                    print("bad")
            elif lattice_id == 0:
                if fire_id == 1 and lever_id != 2 and lever_id != 4:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                elif fire_id == 2 and (lever_id == 2 or lever_id == 4):
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                else:
                    col_error += 1
                    print("bad")
        elif room_id % 2 == 0 and player_mode == 2:
            print("Aaaa")
            if lattice_id == 1:
                if room_id < 4 and fire_id == 3:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                elif room_id > 3 and room_id < 7 and fire_id == 2:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                elif room_id > 6 and fire_id == 1:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                else:
                    col_error += 1
                    print("bad")
            elif lattice_id == 0:
                if fire_id == 3 and lever_id != 2 and lever_id != 4:
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                elif fire_id == 2 and (lever_id == 2 or lever_id == 4):
                    fire_clear = True
                    print("it's good")
                    win_col_quest -= 1
                else:
                    col_error += 1
                    print("bad")
        elif player_mode == 1:
            if fire_id == fire_size_for_win_P1 and lever_action_id_for_win_P1 != win_col_quest:
                fire_clear = True
                print("it's good")
                win_col_quest -= 1
            else:
                col_error += 1
                print("bad")

            

    labelfire_around.place_forget()
    fire_frame_id = (int(fire_id) - 1) % len(fire_around_images)
    labelfire_around.config(image=fire_around_images[fire_frame_id])
    labelfire_around.image = fire_around_images[fire_frame_id] 
    labelfire_around.place(x=420, y=225)

def logic_water_machine(active):
    global water_machine_clear, water_machine_water_col, col_error, win_col_quest
    print("active =", active)
    if active == "up" and water_machine_water_col < 10:
        water_machine_water_col += 1
    elif active == "down" and water_machine_water_col > 0:
        water_machine_water_col -= 1
    elif active == "strong" and water_machine_clear == False:
            if player_mode == 2:
                if lattice_id == 1 and water_machine_water_col == room_id and lever_id != 1:
                    water_machine_clear = True
                    print("it's good")
                    print("1")
                    win_col_quest -= 1
                    labelwater_machine_around.config(image=water_machine_around_images[1])
                    sound_WM_clear.play(loops=0)
                elif water_machine_water_col > 7 and water_machine_water_col == room_id and lever_id == 1:
                    water_machine_clear = True
                    print("it's good")
                    print("4")
                    win_col_quest -= 1
                    labelwater_machine_around.config(image=water_machine_around_images[1])
                    sound_WM_clear.play(loops=0)
                else:
                    col_error += 1
                    print("bad")
            elif player_mode == 1:
                if water_machine_water_col == room_id and lever_action_id_for_win_P1 != win_col_quest:
                    water_machine_clear = True
                    print("it's good")
                    win_col_quest -= 1
                    labelwater_machine_around.config(image=water_machine_around_images[1])
                    sound_WM_clear.play(loops=0)
                else:
                    col_error += 1
                    print("bad")
    elif active == "normal" and water_machine_clear == False:
            if lattice_id == 0 and water_machine_water_col == room_id and lever_id != 1:
                water_machine_clear = True
                print("it's good")
                print("2")
                win_col_quest -= 1
                labelwater_machine_around.config(image=water_machine_around_images[1])
                sound_WM_clear.play(loops=0)
            elif lattice_id == 1 and water_machine_water_col == room_id and lever_id == 1:
                water_machine_clear = True
                print("it's good")
                print("5")
                win_col_quest -= 1
                labelwater_machine_around.config(image=water_machine_around_images[1])
                sound_WM_clear.play(loops=0)
            else:
                col_error += 1
                print("bad")
    elif active == "weak" and water_machine_clear == False:
            if water_machine_water_col > 7 and water_machine_water_col == room_id and lever_id != 1:
                water_machine_clear = True
                print("it's good")
                print("3")
                win_col_quest -= 1
                labelwater_machine_around.config(image=water_machine_around_images[1])
                sound_WM_clear.play(loops=0)
            elif lattice_id == 0 and water_machine_water_col == room_id and lever_id == 1:
                water_machine_clear = True
                print("it's good")
                print("6")
                win_col_quest -= 1
                labelwater_machine_around.config(image=water_machine_around_images[1])
                sound_WM_clear.play(loops=0)
            else:
                col_error += 1
                print("bad")
    
    labelwater_machine_indicator.config(image=water_machine_indicator_images[water_machine_water_col])
    if player_mode == 1:
        text_menu2.config(text=str(water_machine_water_col),  font=("Calibri", 50), background="#767676", foreground="#0300C9")
        text_menu2.place(x=800,y=400)
        text_menu2.lift()
        if water_machine_water_col == 10:
            text_menu2.config(font=("Calibri", 35))
            text_menu2.place(x=790,y=420)
        else:
            text_menu2.config(font=("Calibri", 50))
            text_menu2.place(x=800,y=400)

lattice_anim = Image.open(path_to_game + "\\images\\lattice_anim.png")

width, height = lattice_anim.size

lattice_anim_sprite_parts = []
for y in range(0, height, 400):
    for x in range(0, width, 500):
        box = (x, y, min(x + 500, width), min(y + 400, height))
        sprite = lattice_anim.crop(box)
        lattice_anim_sprite_parts.append(sprite)
lattice_anim_images = [ImageTk.PhotoImage(sp) for sp in lattice_anim_sprite_parts]

labellattice_anim = ttk.Label(root, background='#ca8600')
labellattice_anim.grid(row=0, column=0)

def function_win_level():
    global frame, record_level1_P1, record_level1_P2, stage_other
    reset_FWL_id = root.after(500, function_win_level)
    if win_col_quest == 0:
        frame += 1
        print("Your win!!!!!!")
        labellattice_anim.config(image=lattice_anim_images[frame])
        labellattice_anim.place(x=370, y=225)
        helper_switch_stage("game_level")
        labellattice.place_forget()
        if (lattice_id == 0 and frame > 5) or (lattice_id == 1 and frame > 10):
            print("Stopping loop")
            root.after_cancel(reset_FWL_id)
            stage_other = "menu"
            func = lambda: helper_switch_stage("menu_level_win")
            func()
            labellever.place_forget()
            labellattice.place_forget()
            labellever_around.place_forget()
            labelfire.place_forget()
            labelfire_around.place_forget()
            fire_button_up.place_forget()
            fire_button_yes.place_forget()
            fire_button_down.place_forget()
            labelwater_machine.place_forget()
            labelwater_machine_around.place_forget()
            labellattice_anim.place_forget()
        if player_mode == 1:
            record_level1_P1 = str(time_minutes_level) + ":" + str(time_seconds_level)
        if player_mode == 2:
            record_level1_P2 = str(time_minutes_level) + ":" + str(time_seconds_level)
    elif col_error > 2 or time_minutes_level < 0:
        root.after_cancel(reset_FWL_id)
    else:
        print("Your not win......")
        print(win_col_quest)
        frame = lattice_id * 6

root.bind('<KeyPress>', logic_lever)
root.bind('<KeyRelease>', logic_lever)

reset_timer_id = root.after(50, reset_timer_lever)

menu_show_images()
menu_animations()
root.mainloop()